import React, { useEffect, useState } from "react";
import { InfiniteScroll, PullToRefresh, List, DotLoading } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import styles from './index.module.less'
import { EyeFill } from 'antd-mobile-icons';
import DetailModal from '@/components/detail-modal'
import { showErrorToast } from '@/utils/customToast'
const { getRecommendList, getSettings } = $globalServicer('home')

const GetPullToRefreshlData = (props) => {
  const { itemKey } = props;
  const PageSize = 10; // 每页加载的数据条数
  const [page, setPage] = useState(1); // 当前页码
  const [listData, setListData] = useState([]); // 列表数据
  const [hasMore, setHasMore] = useState(false); // 是否有更多数据
  const [refreshing, setRefreshing] = useState(false); // 刷新状态
  const [loading, setLoading] = useState(false); // 加载状态
  const customNavigate = $globalNavigate()
  const [settingInfo, setSettingInfo] = useState(null)
  
  // 弹窗相关状态
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedWorldId, setSelectedWorldId] = useState(null);
  const fetchSettings = () => {
    getSettings('system_notice').then(res => {
      setSettingInfo(res)
    })
  }
  const fetchData = async (page, size) => {
    try {
      const response = await getRecommendList({ page, size })
      return response.data; // 假设返回的 data 是列表数据
    } catch (error) {
      showErrorToast("加载失败，请稍后再试");
      return [];
    }
  };
  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span style={{ fontSize: '16px' }}>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span style={{ fontSize: '16px' }}>--- 已到达底部 ---</span>
        )}
      </>
    )
  }
  // 加载更多数据的逻辑
  const loadMoreData = async () => {
    if (!hasMore || loading) return;
    setLoading(true); // 设置加载状态为 true
    const newData = await fetchData(page, PageSize);
    if (newData.length < PageSize) {
      setHasMore(false); // 如果返回数据少于 pageSize，则表示没有更多数据
    }

    setListData((prevData) => [...prevData, ...newData]); // 累加新数据
    setPage((prevPage) => prevPage + 1); // 更新页码
    setLoading(false); // 结束加载状态
  };

  // 首次加载数据
  useEffect(() => {
    // loadMoreData(); // 组件挂载时加载数据
    fetchSettings()
    setPage(1); // 重置页码
    setListData([]); // 清空当前列表
    setHasMore(true); // 重置更多数据标志
    loadMoreData(); // 加载新分类的数据
  }, [itemKey]);
  // 下拉刷新逻辑
  const handleRefresh = async () => {
    setRefreshing(true);
    const refreshedData = await fetchData(1, PageSize); // 重新加载第一页的数据
    setListData(refreshedData);
    setPage(2); // 重置页码
    setHasMore(true); // 恢复更多数据的标志
    setRefreshing(false);
  };

  // 处理列表项点击事件
  const handleItemClick = (worldId) => {
    setSelectedWorldId(worldId);
    setModalVisible(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    setSelectedWorldId(null);
  };
  return (
    <div style={{ height: '100%', overflowY: 'scroll' }}>
      <PullToRefresh
        key={itemKey}
        onRefresh={handleRefresh}
        refreshing={refreshing}
      >
        <div className={styles.listWrapper}>
          <div className={styles.listWrapperHeader}>
            {/* <div className={styles.desc}>{settingInfo?.key}</div> */}
            <div className={styles.desc}>
              <p>{settingInfo?.value}</p>
            </div>
          </div>
          <List>
            {listData.map((item, index) => (
              <List.Item
                key={item.id}
                className={styles.classifyItme}
                style={{ backgroundImage: `url(${item.cover})`, backgroundSize: 'cover' }}
                arrowIcon={false}
                onClick={() => handleItemClick(item.id)}
              >
                <div className={styles.itemContent}>
                  {item.title}
                </div>
              </List.Item>
            ))}
          </List>
          <InfiniteScroll loadMore={loadMoreData} hasMore={hasMore} threshold={20} >
            <InfiniteScrollContent hasMore={hasMore} />
          </InfiniteScroll>
        </div>
      </PullToRefresh>
      
      {/* 详情弹窗 */}
      <DetailModal 
        visible={modalVisible}
        onClose={handleCloseModal}
        worldId={selectedWorldId}
      />
    </div>
  );
};

export default GetPullToRefreshlData;
